package com.lovo;

import java.sql.*;

public class Test03 {
    public Connection getConnection(){
        Connection con = null;
        try {
            // 1. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 创建连接
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/j189?userSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT",
                    "root","lovo");

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    public void close(Connection con, Statement statement, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(con != null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public void close(Connection con,Statement statement){
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(con != null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public void testTransition(){
        Connection con = getConnection();
        PreparedStatement statement = null;
        String sql = "update t_student set s_score=? where s_id=?";
        try {
            con.setAutoCommit(false);
            statement = con.prepareStatement(sql);
            statement.setObject(1,75);
            statement.setObject(2,8);
            statement.executeUpdate();
            int a = 100/0;
            statement = con.prepareStatement(sql);
            statement.setObject(1,35);
            statement.setObject(2,9);
            statement.executeUpdate();
            con.commit();
        } catch (SQLException throwables ) {
//            throwables.printStackTrace();
//            try {
//                con.rollback();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
        } catch(Exception e){
//            try {
//                con.rollback();
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }

        }finally {
            close(con,statement);
        }
    }
    public static void main(String[] args) {
        Test03 test03 = new Test03();
        test03.testTransition();
    }
}
